<?php
namespace wow\controller;
use \gnomephp\message\Message;
use \gnomephp\doctrine\Doctrine;


class News extends BaseController{

	const NEWS_ON_INDEX = 9;
	
	public function __construct(){
		parent::__construct();
		
		$this->lang->load('comment');
		$this->lang->load('news');
	}
	
	public function index(){
		
		$news = \wow\model\News::getNews(News::NEWS_ON_INDEX);
		
		
		
		$this->view->assign('news', $news);
		
		
		
		$this->view->render('news/index');
		
	}
	
	
	public function view($id, $title, $replyTo=0){
		
		$news = \wow\model\News::getNewsitem($id);
		
		
		$reply = null;
		if ($replyTo){
			$reply = \wow\model\Comment::getComment($replyTo);
		}
				
		
		$captcha = $this->captcha;
		$user = $this->user;
		$self =$this;
		$form = $this->view->createForm('commentForm', $this->view->url->linkTo('News','view', array('id' => $id, 'title' => $title)), 'post', 
		function($input) use ($captcha, $user, $news, $self){
			if (!$user){
				Message::add(Message::ERROR,'Only registered users is allowed to post comments');
				return;
			}
			try{
				$comment = $input->post->get('comment', function($config){
					$config->set('HTML.Allowed', "strong,b");
				})->required()->validate('Comment');
				
				
				
				$com = new \wow\model\Comment($comment);
				
				if ($user){
					
					$com->setAccountId($user->getID());
					
				}

				if ($replyid = $input->post->get('replyTo')->getData()){
					if ($replyid !== null){
						$reply = \wow\model\Comment::getComment($replyid);
						$com->setParent($reply);
					}
				}
				
				
				$news->addComment($com);
				
				
				Doctrine::load();

				Doctrine::getEM()->persist($com);
				Doctrine::getEM()->persist($news);
				Doctrine::getEM()->flush();
				
				
				Message::add(Message::SUCCESS, 'Thanks for you reply.');

				if (isset($reply)){
					$self->redirect($self->view->url->linkTo('News','view', array('id' => $news->getID(), 'title' => $news->getUrl()   ) ) );
				}
				
			}catch(\gnomephp\input\DataFieldValidException $e){
				Message::add(Message::ERROR, implode($e->getErrors(), '<br />'));
			}
			
		});
		
		$form->rememberPostValues();
		

		$this->view->assign('reply', $reply);
		
		$this->view->assign('newsadmin', $this->hasPermissionTo('news_admin'));
		
		$this->view->assign('commentForm', $form);
		$this->view->assign('news', $news);
		
		
		$this->view->render('news/view');
		
	}
	
	
}